import { mapState, mapMutations } from 'vuex'
import lodash from 'lodash'
import { reverseDate,getNewToken } from '../../config/util'

import Loading from "../../components/loading/loading.vue"
import DatePanel from "../../components/datePanel/datePanel.vue"
import netError from "../../components/netError/netError.vue"
import noShopping from "../../components/noShopping/noShopping.vue"
export default {
	name: 'flightBack',
	data() {
		return {
			noShopping:false,//搜索结果为空组件
			netError:false,//网络连接失败组件
			loading:true,//搜索加载loading
			
			asTime:false,//按照时间排序
			asPrice:true,//按照价格排序
			flightData: [],
			orderByText:{
				time:"时间",
				price:"价格"
			},
			orderByActive:{
				time:false,
				price:false
			}
		}
	},
	computed: {
		...mapState([
			'city', 'Date', 'cabin', 'isBack', 'adultCount','isInland','flight','interRT','token'
		]),
		
	},
	methods: {
		...mapMutations([
			'RECORD_FLIGHT','RECORD_TOKEN'
		]),
		selectTheFlight(flight) {			
			if(this.isInland){
				this.RECORD_FLIGHT({type:"inlandBack",value:flight});
			}else{
				this.RECORD_FLIGHT({type:"inter",value:flight});
			}
			this.$router.push({ path: '/cabin' });
		},
		reChoose(){
			this.$router.push({ path: '/flight' });
		},
		getParams() {
			let data = {
				deptCity: this.city.arrCityCode,
				arrCity: this.city.depCityCode,
				deptStartDate: this.Date.postArrDate,
				deptEndDate: this.Date.postDepDate,
				seatClass: this.cabin?"Y":"FC",
				routingType: "",
				adtCnt: this.adultCount,
				chdCnt: "0",
				infCnt: "0",
				sortType: "price_asc",
			}
			if(!this.isInland&&this.isBack) data.routingType = "RT";				
			else data.routingType = "OW";
			return data;
		},
		successHandle(data) {
			if(data.status == 1001) {
				/*if(this.isInland&&this.cabin){//国内经济舱做价格过滤      //废除此规则
					this.inlandYCabinFilter(data.data)
				}else{
					this.flightData = data.data;
				}	*/
				this.flightData = data.data;
				this.asPrice = false;
				this.filterAsPrice();//默认价格从低到高排序
			} else {
				if(data.status == 1002){
					this.noShopping = true;
				}
				if(!data.status){
					this.netError = true;
				}
			}
		},
		inlandYCabinFilter(data){
			var result = [];
			for(var i=0;i<data.length;i++){
				var prices = data[i].prices;
				//若只有两个以内的价格 直接展示
				if(prices.length<=2){
					result.push(data[i]);
					continue;
				}
				//若有两个以上的价格 则做过滤，展示最低价和做高价，若最低价位淘宝京杭，则同时展示天地行最低价				
				var adultFacePriceArr = [];
				for(var j=0;j<prices.length;j++){
					var adultFacePrice = prices[j].adultFacePrice;
					adultFacePriceArr.push(adultFacePrice);
				}
				var adultFacePriceMax = Math.max.apply(null,adultFacePriceArr);
				var adultFacePriceMin = Math.min.apply(null,adultFacePriceArr);
				var prices_ = [];
				for(var j=0;j<adultFacePriceArr.length;j++){
					//最高价
					if(adultFacePriceArr[j]==adultFacePriceMax){
						prices_.push(prices[j]);
					}
					//最低价
					if(adultFacePriceArr[j]==adultFacePriceMin){
						prices_.push(prices[j]);
						//若最低价位淘宝京杭，则同时展示天地行最低价
						if(prices[j].supplierId=='JHAD'){
							var r = TDXDminPrice(prices);
							prices_.push(r);
						}
					}
				}
				var t = JSON.parse(JSON.stringify(data[i]));
				t.prices = prices_;
				result.push(t);
			}
			//返回结果
			this.flightData = result;
			//筛选天地行最低价
			function TDXDminPrice(prices){
				var TDXDPrice = [];
				for(var n=0;n<prices.length;n++){
					if(prices[n].supplierId=='TDXD'){
						TDXDPrice.push(prices[n].adultFacePrice);
					}
				}
				var res = Math.min.apply(null,TDXDPrice);
				for(var n=0;n<prices.length;n++){
					if(prices[n].adultFacePrice==res){
						return prices[n];
					}
				}
			}
		},
		errorHandle(res) {
			
		},
		flightDuration(value){
			var duration = 0;
			for(var i=0;i<value.length;i++){
				duration+=value[i].flightDuration;
			}
			return duration;
		},
		//跨天
		acrossDay(flight){
			let rangeSegmentCount = flight.rangeSegmentCount;
			let legs = rangeSegmentCount.split(",")[0].split("-")[1];
			let fromDate = flight.segments[0].fromDate.substring(0,10);
			let toDate = flight.segments[legs-1].toDate.substring(0,10);
			let count = parseInt((reverseDate(toDate) - reverseDate(fromDate))/86400000);
			return count;
		},
		imgName(flight){
			var name = (flight.segments[0].flightNo).slice(0,2);			
			return name+".PNG";
		},
		tranformTime(flight){
			let rangeSegmentCount = flight.rangeSegmentCount;
			let legs = rangeSegmentCount.split(",")[0].split("-")[1];
			if(legs>1){
				var toDate = flight.segments[0].toDate;
				var fromDate = flight.segments[1].fromDate;
				var min = (reverseDate(fromDate) - reverseDate(toDate)) / 60000;
				return min;
			}			
		},
		arrivedMess(flight){
			let rangeSegmentCount = flight.rangeSegmentCount;
			let rangeSegmentCountStr = rangeSegmentCount.split(",")[0];
			let index = rangeSegmentCountStr.charAt(rangeSegmentCountStr.length-1)
			let toDate = flight.segments[index-1].toDate;
			let toAirportCn = flight.segments[index-1].toAirportCn;
			let toTower = flight.segments[index-1].toTower;
			return {toDate:toDate,toAirportCn:toAirportCn,toTower:toTower};			
		},
		screen(){
			alert("1")
		},
		filterAsTime(){
			this.asPrice = false;
			this.orderByActive = {time:true,price:false};
			if(this.asTime){	
				this.orderByText = {time:'从早到晚',price:'价格'};
				this.flightData = _.orderBy(this.flightData, 'segments[0].fromDate'); //由低到高
			}else{
				this.orderByText = {time:'从晚到早',price:'价格'};
				this.flightData = _.orderBy(this.flightData, 'segments[0].fromDate').reverse();//由高到低
			}				
			this.asTime = !this.asTime;
		},
		filterAsPrice(){
			this.asTime = true;
			this.orderByActive = {time:false,price:true};
			if(this.asPrice){
				this.orderByText = {time:'时间',price:'从高到低'};
				this.flightData = _.orderBy(this.flightData, 'minAdultFacePrice').reverse(); //由低到高	
			}else{
				this.orderByText = {time:'时间',price:'从低到高'};
				this.flightData = _.orderBy(this.flightData, 'minAdultFacePrice'); //由高到低
			}		
			this.asPrice = !this.asPrice;		
		},
		deleteBackRouteData(){
			if(this.flight.inland.length==2) this.RECORD_FLIGHT({type:"deleteBackRouteData"});							
		},
		//获取数据
		loadData(){
			this.$axios.get('/shopping/query', {
				params: this.getParams(),
				headers: {'authorization':this.token}
			})
				.then((res) => {
					this.RECORD_TOKEN({type:"update",val:getNewToken(res.headers)});
					this.loading = false;
					this.successHandle(res.data);
				})
				.catch((error) => {
					this.errorHandle(res)
				})		
		},
		//与日期子组件交互
		load(){
			this.loading = true;
			this.loadData();
		},
		/*判断是否经停*/
		stopOver(flight){
			var directFlight = flight.directFlight;
			if(!directFlight) return {show:false};//优先展示中转
			var length = flight.segments[0].stopOver.length;
			if(length==0) return {show:false};
			if(length == 1){
				return {show:true,city:flight.segments[0].stopOver[0].stopAirport}
			}else if(length == 2){
				return {show:true,city:'2次',color:true}
			}else{
				return {show:true,city:'多次'}
			}	
		},
		/*判断是否中转*/
		directFlight(flight){
			var rangeSegmentCount = flight.rangeSegmentCount;
			var segmentCount = rangeSegmentCount.split(",")[0].split("-")[1];
			if(segmentCount == 1){
				return {show:false}
			}else if(segmentCount == 2){
				return {show:true,city:flight.segments[0].toCityCn}
			}else if(segmentCount == 3){
				return {show:true,city:'2次',color:true}
			}else{
				return {show:true,city:'多次'}
			}			
		},		
		//与netError子组件交互
		netErrorClose(){
			this.netError = false;
		},
	},
	components:{
	  	Loading,
	  	DatePanel,
	  	netError,
	  	noShopping,
	},
	created() {	
		document.title = "选回程 "+this.city.arrCity+"—"+this.city.depCity;	
		//返回至国内返程页面后删除原信息
		this.deleteBackRouteData();		
		this.loadData();	
	}
}